package cybertechcebu.task
{
	import cybertechcebu.Console;
	import cybertechcebu.FTPClient;
	import cybertechcebu.FTPCommand;
	import cybertechcebu.FTPResponse;
	import cybertechcebu.RemoteFile;
	import cybertechcebu.enum.Commands;
	import cybertechcebu.enum.Responses;
	
	import flash.events.Event;
	import flash.events.ProgressEvent;
	
	public class ListDirTask extends Task
	{
		private var directory:String;
		private var listingReceived:Boolean = false;
		
		public function ListDirTask(client:FTPClient, directory:String = "")
		{
			super(client);
			this.directory = directory;
		}
		
		override protected function startTask():void
		{
			sendCommand(new FTPCommand(Commands.PASV));
		}
		
		override public function handleResponse(response:FTPResponse):void
		{
			switch (response.code)
			{
				case Responses.ENTERING_PASV:
					
					createDataSocket(response);
					
					break;
				case Responses.DATA_CONN_CLOSE:
					
					break;
				case Responses.FILE_STATUS_OK:
					
					break;
				case Responses.DATA_CONN_ALREADY_OPEN:
					
					break;
				case Responses.NOT_FOUND:
					
					break;
				case Responses.FILE_ACTION_OK:
					
					break;
				default:
					dispatchTaskError("Unhandled response code: " + response.code);
			}
		}
		
		private function createDataSocket(response:FTPResponse):void{
			
			initDataSocket();
			
			addConnectHandler(function(e:Event):void
			{
				sendCommand(new FTPCommand(Commands.LIST, directory));
			});
			
			addDataHandler(handleListing);
			
			addCloseHandler(function(e:Event):void
			{
				if (!listingReceived)
				{
					client.remoteFileList = [];
				}
				dispatchTaskEnd(true);
			});
			
			connect(response.str);
	
		}
		
		private function handleListing(e:ProgressEvent):void
		{
			var listing:String = dataSocket.readUTFBytes(dataSocket.bytesAvailable);
			var fileList:Array = parseFromListing(listing, directory);
			client.remoteFileList = fileList;
			listingReceived = true;
		}
		
		protected function parseFromListing(listing:String, dir:String):Array
		{
			var list:Array = [];
			var rawList:Array = listing.match(/^.+/gm);
			var i:int = rawList.length;
			
			while (i--){
				list.push(parseFromListEntry(rawList[i], dir));
			}
			return list;
		}
		
		protected static function parseFromListEntry(entry:String, dir:String):RemoteFile
		{
			var file:RemoteFile = new RemoteFile();
			var fields:Array = entry.split(/ +/g);
			var isDir:Boolean = entry.charAt(0).toLowerCase() == "d";
			var name:String = entry.substring(entry.indexOf(':') + 4, entry.length);
			var path:String = dir;
			var size:int = parseInt(fields[4]);
					
			return new RemoteFile(name, path, size, isDir);
		}
		
	}
}
